package com.newlink.building.common_base.utils

import android.annotation.SuppressLint
import android.app.Activity
import android.app.AppOpsManager
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.provider.Settings
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader
import java.lang.reflect.Method


/**
 * @Author: Jake
 * @Date: 2024-03-07
 * @Description:
 */
object RomUtils {
    private val TAG = RomUtils::class.java.simpleName

    fun isXiaoMi(): Boolean {

        return checkManufacturer("xiaomi")
    }

    fun isOppo(): Boolean {

        return checkManufacturer("oppo")
    }

    fun isSamsung(): Boolean {

        return checkManufacturer("samsung")
    }

    fun isVivo(): Boolean {

        return checkManufacturer("vivo")
    }

    fun isHuawei(): Boolean {

        return checkManufacturer("huawei")
    }

    private fun checkManufacturer(manufacturer: String): Boolean {
        return manufacturer.equals(Build.MANUFACTURER, true)
    }

    fun getManufacturer(): String {
        return Build.MANUFACTURER
    }

    fun getBrand(): String {
        return Build.BRAND
    }

    fun isBackgroundStartAllowed(context: Context): Boolean {
        if (isXiaoMi()) {
            NLog.e("[jake] devices is xiaomi")
            return isXiaomiBgStartPermissionAllowed(context)
        }

        if (isVivo()) {
            NLog.e("[jake] devices is isVivo")
            return isVivoBgStartPermissionAllowed(context)
        }

        if (isOppo() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            NLog.e("[jake] devices is isOppo")
            return Settings.canDrawOverlays(context)
        }
        NLog.e("[jake] devices is other!")
        return true
    }


    private fun isXiaomiBgStartPermissionAllowed(context: Context): Boolean {
        val ops = context.getSystemService(Context.APP_OPS_SERVICE) as AppOpsManager
        try {
            val op = 10021
            val method: Method =
                ops.javaClass.getMethod(
                    "checkOpNoThrow",
                    Int::class.javaPrimitiveType,
                    Int::class.javaPrimitiveType,
                    String::class.java
                )
            val result =
                method.invoke(ops, op, android.os.Process.myUid(), context.packageName) as Int
            return result == AppOpsManager.MODE_ALLOWED
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return false
    }

    private fun isVivoBgStartPermissionAllowed(context: Context): Boolean {
        return getVivoBgStartPermissionStatus(context) == 0
    }

    fun requestXiaomiBgStartPermission(context: Activity, requestCode: Int): Boolean {

        try {
            NLog.d("jake ... jumpSettings 111111111")
            val intent = Intent("miui.intent.action.APP_PERM_EDITOR")
            intent.putExtra("extra_pkgname", context.packageName)
            val componentName = ComponentName(
                "com.miui.securitycenter",
                "com.miui.permcenter.permissions.PermissionsEditorActivity"
            )
            intent.component = componentName
            context.startActivityForResult(intent, requestCode)
            return true
        } catch (e: Exception) {
            try {
                NLog.d("jake ... jumpSettings 22222222222222")
                e.printStackTrace()
                val intent = Intent()
                intent.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
                val uri = Uri.fromParts("package", context.packageName, null)
                intent.data = uri
                context.startActivityForResult(intent, requestCode)
                return true
            } catch (e2: Exception) {

            }
        }
        return false
    }

    fun goXiaoMiManager(activity: Activity) {
        val rom: String = getMiuiVersion(activity)
        NLog.d("jake ... jumpSettings XIAOMI ROM IS $rom")
        val intent = Intent()
        if ("V6" == rom || "V7" == rom) {
            intent.action = "miui.intent.action.APP_PERM_EDITOR"
            intent.setClassName(
                "com.miui.securitycenter",
                "com.miui.permcenter.permissions.AppPermissionsEditorActivity"
            )
            intent.putExtra("extra_pkgname", activity.packageName)
        } else if ("V8" == rom || "V9" == rom) {
            intent.action = "miui.intent.action.APP_PERM_EDITOR"
            intent.setClassName(
                "com.miui.securitycenter",
                "com.miui.permcenter.permissions.PermissionsEditorActivity"
            )
            intent.putExtra("extra_pkgname", activity.packageName)
        } else {
            goIntentSetting(activity)
        }

    }

    private fun getMiuiVersion(activity: Activity): String {
        val propName = "ro.miui.ui.version.name"
        val line: String
        var input: BufferedReader? = null
        try {
            val p = Runtime.getRuntime().exec("getprop $propName")
            input = BufferedReader(
                InputStreamReader(p.inputStream), 1024
            )
            line = input.readLine()
            input.close()
        } catch (ex: IOException) {
            ex.printStackTrace()
            return ""
        } finally {
            try {
                input!!.close()
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }
        return line
    }

    private fun goIntentSetting(activity: Activity) {
        val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
        val uri = Uri.fromParts("package", activity.packageName, null)
        intent.data = uri
        try {
            activity.startActivity(intent)
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
        }
    }

    fun requestVivoBgStartPermission(context: Activity, requestCode: Int): Boolean {
        try {
            val str = Build.MODEL
            if ((!str.contains("Y85") || str.contains("Y85A"))
                && !str.contains("Y53L")
                && !str.contains("Y67A")
            ) {
                val intent = Intent().apply {
                    setClassName(
                        "com.vivo.permissionmanager",
                        "com.vivo.permissionmanager.activity.SoftPermissionActivity"
                    )
                    action = "secure.intent.action.softPermissionDetail"
                    putExtra("pkgname", context.packageName)
                }
                context.startActivityForResult(intent, requestCode)
            } else {
                val intent2 = Intent().apply {
                    setClassName(
                        "com.vivo.permissionmanager",
                        "com.vivo.permissionmanager.activity.PurviewTabActivity"
                    )
                    putExtra("pkgname", context.packageName)
                    putExtra("tabId", "1")
                }
                context.startActivityForResult(intent2, requestCode)
            }
            return true
        } catch (e: Exception) {
            try {
                val intent = getRightIntent(context)
                if (intent != null) {
                    context.startActivityForResult(intent, requestCode)
                    return true
                }
            } catch (e: Exception) {

            }
        }
        return false
    }

    fun getRightIntent(context: Context?): Intent? {
        val intentList = getIntentList(context!!)
        if (intentList!!.isEmpty()) {
            return null
        }
        for (intent in intentList) {
            if (hasIntent(context, intent)) {
                return intent
            }
        }
        return null
    }

    fun getIntentList(context: Context): List<Intent?>? {
        val arrayList: ArrayList<Intent> = ArrayList<Intent>()
        val intent = Intent()
        intent.putExtra("packagename", context.packageName)
        intent.component = ComponentName(
            "com.vivo.permissionmanager",
            "com.vivo.permissionmanager.activity.SoftPermissionDetailActivity"
        )
        arrayList.add(intent)
        val intent2 = Intent()
        intent2.putExtra("packagename", context.packageName)
        intent2.component =
            ComponentName("com.iqoo.secure", "com.iqoo.secure.ui.phoneoptimize.FloatWindowManager")
        arrayList.add(intent2)
        val intent3 = Intent()
        intent3.component = ComponentName(
            "com.vivo.permissionmanager",
            "com.vivo.permissionmanager.activity.PurviewTabActivity"
        )
        arrayList.add(intent3)
        val intent4 = Intent()
        intent4.component = ComponentName("com.iqoo.secure", "com.iqoo.secure.MainActivity")
        arrayList.add(intent4)
        val intent5 = Intent()
        intent5.component = ComponentName("com.iqoo.secure", "com.iqoo.secure.MainGuideActivity")
        arrayList.add(intent5)
        return arrayList
    }

    fun hasIntent(context: Context, intent: Intent?): Boolean {
//        return context.packageManager.queryIntentActivities(intent!!, 4096).size > 0
        return context.packageManager.queryIntentActivities(
            intent!!,
            PackageManager.GET_META_DATA
        ).size > 0
    }

    /**
     * 判断Vivo后台弹出界面状态， 1无权限，0有权限
     * @param context context
     */
    @SuppressLint("Range")
    private fun getVivoBgStartPermissionStatus(context: Context): Int {
        val uri: Uri =
            Uri.parse("content://com.vivo.permissionmanager.provider.permission/start_bg_activity")
        val selection = "pkgname = ?"
        val selectionArgs = arrayOf(context.packageName)
        var state = 1
        try {
            context.contentResolver.query(uri, null, selection, selectionArgs, null)?.use {
                if (it.moveToFirst()) {
                    state = it.getInt(it.getColumnIndex("currentstate"))
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return state
    }
}
